package com.njbw.design_pattern.created.prototype.deepCopy;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.time.LocalDate;

/**
 * 深拷贝原型模式
 *
 * @author 黄侯淳
 * @since JDK 1.8
 */
@Slf4j
public class Main2 {

    @SneakyThrows
    public static void main(String[] args) throws CloneNotSupportedException {
        PromotionEvent promotionEvent = new PromotionEvent();
        promotionEvent.setStartDate(LocalDate.now());

        PromotionRule promotionRule = new PromotionRule();
        promotionRule.setType("折扣");
        promotionRule.setDiscount(0.9);

        Product product = new Product();
        promotionRule.setProduct(product);

        promotionEvent.addRule(promotionRule);

        // 深拷贝
        // 1、将对象转换为二进制流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(promotionEvent);
        byte[] byteArray = bos.toByteArray();

        // 2、将二进制流转换为新的对象
        // 使用字节流进行反序列化，得到一个实例
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArray));
        PromotionEvent clonePromotionEvent = (PromotionEvent) ois.readObject();

        // 3.测试
        log.info(clonePromotionEvent.getRuleList().get(0).getProduct() == promotionEvent.getRuleList().get(0).getProduct() ? "浅拷贝" : "深拷贝");
        // 通过拷贝已有的旧的规则，修改部分规则变成一个新的活动（部分定制）
        clonePromotionEvent.getRuleList().get(0).setDiscount(0.7);
    }
}
